package com.ah.shanxi_demo.service.impl;

import com.ah.shanxi_demo.common.TimeUtils;
import com.ah.shanxi_demo.common.enums.PolicyCommonEnum;
import com.ah.shanxi_demo.entity.SxPolicy;
import com.ah.shanxi_demo.entity.SxRegister;
import com.ah.shanxi_demo.mapper.SxPolicyMapper;
import com.ah.shanxi_demo.mapper.SxRegisterMapper;
import com.ah.shanxi_demo.param.input.PolicyCollectRO;
import com.ah.shanxi_demo.param.input.PolicyPO;
import com.ah.shanxi_demo.param.result.PolicyDataReportMapperPO;
import com.ah.shanxi_demo.param.result.PolicyGeneralRO;
import com.ah.shanxi_demo.service.IPolicyService;
import com.ah.shanxi_demo.sync.param.PolicyDataReportPO;
import com.ah.shanxi_demo.sync.param.result.SyncPolicyResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.*;

import static com.ah.shanxi_demo.common.PageUtils.queryPageIndex;
import static com.ah.shanxi_demo.common.RandomUtils.getRandom;
import static com.ah.shanxi_demo.convert.ConvertPolicy.convert_policy_list;
import static com.ah.shanxi_demo.convert.ConvertPolicyData.merge_convert_policy_data_ro;
import static com.ah.shanxi_demo.sync.client.SyncPolicyClient.policy_client;
import static com.ah.shanxi_demo.sync.client.SyncPolicyDataReportClient.policy_data_client;

/**
 * @author zt 2020/8/16
 */
@Service
public class PolicyService implements IPolicyService {
    private static final Logger log = LoggerFactory.getLogger(RegisterService.class);

    @Autowired
    private SxRegisterMapper registerMapper;

    @Autowired
    private SxPolicyMapper policyMapper;


    @Override
    public List<SxPolicy> listBySelect(PolicyPO policyPO) {

        //获取当前注册表信息 节点唯一标识
        SxRegister sxRegister = registerMapper.selectRecent();
        policyPO.setRegisterId(sxRegister.getRegisterId());

        //分页设置
        policyPO.setPageIndex(queryPageIndex(policyPO.getPageIndex(), policyPO.getPageSize()));

        //list搜索查询
        List<SxPolicy> sxPolicyList = policyMapper.listBySelect(policyPO);

        return sxPolicyList;
    }

    @Override
    public Integer listCountBySelect(PolicyPO policyPO) {
        policyPO.setPageIndex(queryPageIndex(policyPO.getPageIndex(), policyPO.getPageSize()));
        Integer listCountBySelect = policyMapper.listCountBySelect(policyPO);
        return listCountBySelect;
    }

    @Override
    public Boolean deletePolicy(Long[] policyIdList) {
        Arrays.stream(policyIdList).forEach(policyId -> {
            policyMapper.deletePolicy(policyId);
        });
        return Boolean.TRUE;
    }

    @Override
    public SxPolicy selectById(Long policyId) {
        SxPolicy model = policyMapper.selectById(policyId);
        if (model == null) {
            return new SxPolicy();
        }
        return model;

    }

    @Override
    public PolicyGeneralRO general() {
        //获取当前注册表信息 节点唯一标识
        SxRegister sxRegister = registerMapper.selectRecent();

        PolicyGeneralRO model = new PolicyGeneralRO();
        model.setFinished(policyMapper.generalFinish(sxRegister.getRegisterId()));
        model.setUnfinished(policyMapper.generalUnFinish(sxRegister.getRegisterId()));
        return model;
    }

    @Override
    public Boolean collect(PolicyCollectRO policyCollectRO) {

        //查询相关信息（注册表信息）
        PolicyDataReportMapperPO dataReportMapperPO = policyMapper.selectDataReportByPolicyId(policyCollectRO.getPolicyId());

        //拼装数据
        PolicyDataReportPO dataReportPO = merge_convert_policy_data_ro(dataReportMapperPO, policyCollectRO);


        //部级平台数据采集 上报
        Boolean policy_data_client = policy_data_client(dataReportPO, dataReportMapperPO.getService_address());

        if (policy_data_client) {
            //上传成功修改策略状态
            policyMapper.updateStatus(Integer.valueOf(PolicyCommonEnum.STATUS_SUCCESS.getKey()), Long.valueOf(policyCollectRO.getPolicyId()));
        } else {
            //上传成功修改策略状态
            policyMapper.updateStatus(Integer.valueOf(PolicyCommonEnum.STATUS_FAIL.getKey()), Long.valueOf(policyCollectRO.getPolicyId()));
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean simulationCollect(PolicyCollectRO policyCollectRO) {

        Boolean policy_data_client = Boolean.TRUE;

        if (policy_data_client) {
            //上传成功修改策略状态
            policyMapper.updateStatus(Integer.valueOf(PolicyCommonEnum.STATUS_SUCCESS.getKey()), Long.valueOf(policyCollectRO.getPolicyId()));
        } else {
            //上传成功修改策略状态
            policyMapper.updateStatus(Integer.valueOf(PolicyCommonEnum.STATUS_FAIL.getKey()), Long.valueOf(policyCollectRO.getPolicyId()));
        }
        return Boolean.TRUE;
    }

    //同步策略数据
    @Override
    @Transactional
    public void syncPolicy() {

        //获取当前注册表信息 节点唯一标识
        SxRegister sxRegister = registerMapper.selectRecent();

        //调取部级平台生成策略数据
        List<SyncPolicyResult> syncPolicyResults = policy_client(sxRegister);

        //转换为表数据结构
        List<SxPolicy> sxPolicyList = convert_policy_list(syncPolicyResults, sxRegister.getRegisterId());

        //插入策略数据库
        insertPolicyList(sxPolicyList);

    }

    @Override
    public void syncSimulationPolicy() {

        //获取当前注册表信息 节点唯一标识
        SxRegister sxRegister = registerMapper.selectRecent();

        SxPolicy sxPolicy = policyFakeModel();
        sxPolicy.setRegisterId(sxRegister.getRegisterId());

        try {
            policyMapper.insertPolicy(sxPolicy);
        } catch (Throwable e) {
            log.error("PolicyService 【syncSimulationPolicy】" + e.getMessage());
        }
    }

    private SxPolicy policyFakeModel() {
//        INSERT INTO `bigdata-web`.`sx_policy`(`policy_code`, `guid_type`, `guid`, `policy_status`, `log_type`, `policy_type`)
//        VALUES ('110201-20190710-0002', 1, '1', 0, 'alarm', 'ALM-01-3')

//        UPDATE `bigdata-web`.`sx_order` SET `register_id` = 21, `work_code` = '11-20190710-3', `title` = '进行漏洞',
//        `content` = '漏洞', `accdept` = '生成部', `accuser` = '生成人1', `write_user` = '张', `type` = 1,
//        `level` = 4, `scan_type` = 2 WHERE `order_id` = 5
        SxPolicy fakeModel = new SxPolicy();
        fakeModel.setPolicyCode("110201-20190710-0002");
        fakeModel.setGuidType(getRandom(2));
        fakeModel.setGuid("1");
        fakeModel.setLogType("alarm");
        fakeModel.setPolicyType("ALM-01-3");
        fakeModel.setPolicyStatus(0);
        fakeModel.setDelete(0);
        fakeModel.setBeginTime(TimeUtils.parseDate(new Date()));
        fakeModel.setEndTime(TimeUtils.parseDate(new Date()));
        return fakeModel;
    }

    @Override
    @Transactional
    public Boolean insertPolicyList(List<SxPolicy> sxPolicyList) {
        Boolean falseBoolean = Boolean.FALSE;
        if (CollectionUtils.isEmpty(sxPolicyList)) {
            return falseBoolean;
        }
        sxPolicyList.stream().forEach(sxPolicy -> {

            //不重复 插入
            if (policyMapper.selectByRepeat(sxPolicy) == 0) {
                policyMapper.insertPolicy(sxPolicy);
            }
        });

        return Boolean.TRUE;
    }

}
